<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="滚动信息内容" prop="scrollingInfo">
        <el-input
          v-model="queryParams.scrollingInfo"
          placeholder="请输入滚动信息内容"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactInfo">
        <el-input
          v-model="queryParams.contactInfo"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-top: 30px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['checksystem:details:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['checksystem:details:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['checksystem:details:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['checksystem:details:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="el-table-wrapper">
      <el-table v-loading="loading" :data="detailsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="id" />
        <el-table-column label="滚动信息内容" align="center" prop="scrollingInfo" />
        <el-table-column label="VIP套餐展示信息" align="center" prop="vipPackages">
          <template #default="scope">
            <div v-if="scope.row.vipPackages">
              <div v-html="formatVipPackages(scope.row.vipPackages)"></div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="活动到期时间" align="center" prop="expirationDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" align="center" prop="contactInfo" />
        <el-table-column label="说明区域内容" align="center" prop="description" />
        <el-table-column label="客服二维码" align="center" prop="qrCodeUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.qrCodeUrl" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="显示顺序" align="center" prop="displayOrder" />
        <el-table-column label="删除标记" align="center" prop="isDeleted">
          <template #default="scope">
            <el-tag :type="scope.row.isDeleted === 1 || scope.row.isDeleted === '1' ? 'danger' : 'success'">
              {{ scope.row.isDeleted === 1 || scope.row.isDeleted === '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['checksystem:details:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['checksystem:details:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="pagination-container"
    />

    <!-- 添加或修改广告对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="detailsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="滚动信息内容" prop="scrollingInfo">
          <el-input v-model="form.scrollingInfo" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="VIP套餐展示信息" prop="vipPackages">
          <el-input v-model="form.vipPackages" type="textarea" placeholder="请输入JSON格式的套餐信息，例如:[{&quot;duration&quot;:&quot;365天&quot;,&quot;price&quot;:768}]" />
          <div class="el-form-item-tips">格式必须为合法的JSON数组，包含duration和price字段</div>
          <div v-if="form.vipPackages" class="package-preview">
            <div class="preview-title">套餐展示效果预览：</div>
            <div class="preview-content" v-html="formatVipPackages(form.vipPackages)"></div>
          </div>
        </el-form-item>
        <el-form-item label="活动到期时间" prop="expirationDate">
          <el-date-picker clearable
            v-model="form.expirationDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择活动到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactInfo">
          <el-input v-model="form.contactInfo" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="说明区域内容" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="客服二维码URL" prop="qrCodeUrl">
          <image-upload v-model="form.qrCodeUrl"/>
        </el-form-item>
        <el-form-item label="显示顺序" prop="displayOrder">
          <el-input-number v-model="form.displayOrder" :min="0" :max="99" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="删除标记" prop="isDeleted">
          <el-select v-model="form.isDeleted" placeholder="请选择">
            <el-option :label="'否'" :value="0"></el-option>
            <el-option :label="'是'" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Details">
import { listDetails, getDetails, delDetails, addDetails, updateDetails } from "@/api/checksystem/details";
import { ElMessage } from 'element-plus'
import { formatDate } from '@/utils/format'

const { proxy } = getCurrentInstance();

const detailsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    scrollingInfo: null,
    vipPackages: null,
    expirationDate: null,
    contactInfo: null,
    description: null,
    qrCodeUrl: null,
    displayOrder: null,
    createTime: null,
    updateTime: null,
    isDeleted: null
  },
  rules: {
    scrollingInfo: [
      { required: true, message: "滚动信息内容不能为空", trigger: "blur" }
    ],
    vipPackages: [
      { required: true, message: "VIP套餐展示信息不能为空", trigger: "blur" },
      { validator: (rule, value, callback) => {
          try {
            if (value) {
              const parsed = JSON.parse(value);
              if (!Array.isArray(parsed)) {
                callback(new Error('必须是JSON数组格式'));
                return;
              }
              for (const item of parsed) {
                if (!item.duration || !item.price) {
                  callback(new Error('每个套餐必须包含duration和price字段'));
                  return;
                }
              }
            }
            callback();
          } catch (e) {
            callback(new Error('格式错误，必须是合法的JSON'));
          }
        }, trigger: "blur" }
    ],
    expirationDate: [
      { required: true, message: "活动到期时间不能为空", trigger: "blur" }
    ],
    contactInfo: [
      { required: true, message: "联系方式不能为空", trigger: "blur" }
    ],
    qrCodeUrl: [
      { required: true, message: "客服二维码URL不能为空", trigger: "blur" },
      { validator: (rule, value, callback) => {
          if (value && !value.match(/\.(jpeg|jpg|gif|png)$/i)) {
            callback(new Error('请上传JPEG/JPG/GIF/PNG格式的图片'));
            return;
          }
          callback();
        }, trigger: "blur" }
    ],
    displayOrder: [
      { required: true, message: "显示顺序不能为空", trigger: "blur" }
    ],
    isDeleted: [
      { required: true, message: "删除标记不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询广告列表 */
function getList() {
  loading.value = true;
  listDetails(queryParams.value).then(response => {
    detailsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    scrollingInfo: null,
    vipPackages: null,
    expirationDate: null,
    contactInfo: null,
    description: null,
    qrCodeUrl: null,
    displayOrder: null,
    createTime: null,
    updateTime: null,
    isDeleted: null
  };
  proxy.resetForm("detailsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加广告";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDetails(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改广告";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["detailsRef"].validate(valid => {
    if (valid) {
      try {
        // 确保vipPackages是合法的JSON
        if (form.value.vipPackages) {
          JSON.parse(form.value.vipPackages);
        }
        
        if (form.value.id != null) {
          updateDetails(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          }).catch(error => {
            proxy.$modal.msgError(`修改失败: ${error.message || '未知错误'}`);
          });
        } else {
          addDetails(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          }).catch(error => {
            proxy.$modal.msgError(`新增失败: ${error.message || '未知错误'}`);
          });
        }
      } catch (e) {
        proxy.$modal.msgError(`提交失败: ${e.message}`);
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除广告编号为"' + _ids + '"的数据项？').then(function() {
    return delDetails(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('checksystem/details/export', {
    ...queryParams.value
  }, `details_${new Date().getTime()}.xlsx`)
}

/** 格式化VIP套餐显示 */
function formatVipPackages(packagesStr) {
  try {
    if (!packagesStr) return '-';
    
    const packages = typeof packagesStr === 'string' ? JSON.parse(packagesStr) : packagesStr;
    if (!Array.isArray(packages) || packages.length === 0) return '-';
    
    // 根据套餐时长进行排序（从长到短）
    packages.sort((a, b) => {
      // 提取duration中的数字部分
      const daysA = parseInt(String(a.duration).replace(/[^\d]/g, '')) || 0;
      const daysB = parseInt(String(b.duration).replace(/[^\d]/g, '')) || 0;
      return daysB - daysA;
    });
    
    // 构建套餐宣传语
    const packagesHtml = packages.map(pkg => {
      const price = pkg.price || 0;
      const points = pkg.points || 0;
      const duration = String(pkg.duration || '');
      const days = parseInt(duration.replace(/[^\d]/g, '')) || 0;
      
      // 针对不同时长设置不同的宣传语和颜色
      let promotionText = '';
      let color = '';
      
      if (days >= 365) {
        promotionText = `年度尊享套餐`;
        color = '#ff6b00';
      } else if (days >= 180) {
        promotionText = `半年超值套餐`;
        color = '#2b85e4';
      } else if (days >= 88) {
        promotionText = `季度畅享套餐`;
        color = '#5cb85c';
      } else if (days >= 30) {
        promotionText = `月度体验套餐`;
        color = '#19be6b';
      } else {
        promotionText = `限时特惠套餐`;
        color = '#909399';
      }
      
      // 使用简洁的布局，添加轻微的边框和背景，文字居中对齐
      return `<div style="margin-bottom:12px;line-height:1.4;border:1px solid #ebeef5;border-radius:4px;padding:8px;background-color:#fafafa;text-align:center;">
        <div style="color:${color};font-weight:bold;margin-bottom:4px;border-bottom:1px dashed #e0e0e0;padding-bottom:4px;">${promotionText}</div>
        <div>时长: <b>${duration}</b></div>
        <div>价格: <b>${price}元</b></div>
        <div>赠送: <b style="color:#ff4500;">${points}积分</b></div>
      </div>`;
    }).join('');
    
    return packagesHtml;
  } catch (error) {
    console.error('格式化套餐信息失败:', error);
    return '套餐信息格式错误';
  }
}

getList();
</script>

<style>
.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: center;
}

/* 表单样式 */
.el-form--inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
}

.el-form--inline .el-form-item {
  margin: 0;
  display: flex;
  align-items: center;
}

.el-form-item__label {
  white-space: nowrap;
  min-width: 120px;
  line-height: 32px;
}

.el-form-item__content {
  display: flex;
  align-items: center;
}

.el-input__wrapper,
.el-date-editor {
  width: 200px;
  height: 32px;
}

/* 分页样式 */
.pagination-container {
  position: fixed;
  bottom: 0;
  left: 200px;
  right: 0;
  background-color: #fff;
  padding: 15px 20px;
  box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-top: 1px solid #dcdfe6;
}

/* 表格容器样式 */
.el-table-wrapper {
  margin-bottom: 80px;
}
</style>
